<?php
/**
 * Created by PhpStorm.
 * User: wxy
 * Date: 2018/11/13
 * Time: 13:59
 */

namespace frontend\modules\resource\logic;

use common\models\BranchResource;
use common\models\HyAudio;
use common\models\HyBook;
use common\models\HyPeriodical;
use common\models\HyPicture;
use common\models\HyResource;
use common\models\HyVideo;
use common\models\ResourceClasses;
use frontend\modules\common\models\BaseHelper;
use frontend\modules\common\models\BaseParam;
use frontend\modules\common\models\ExcelReader;
use frontend\modules\resource\models\HyAudioSearch;
use frontend\modules\resource\models\HyBookSearch;
use frontend\modules\resource\models\HyPeriodicalSearch;
use frontend\modules\resource\models\HyPictureSearch;
use frontend\modules\resource\models\HyVideoSearch;
use PHPExcel_CachedObjectStorageFactory;
use PHPExcel_IOFactory;
use PHPExcel_Settings;
use Yii;
use yii\db\ActiveRecord;
use yii\helpers\ArrayHelper;
use yii\web\NotFoundHttpException;


class ResourceImportLogic extends ResourceLogic
{

    /**
     * 读取信息
     * @param $path
     * @param $type
     * @return int
     * @throws NotFoundHttpException
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \yii\base\ExitException
     * @throws \yii\db\Exception
     */
//    public function ImportData($path, $type)
//    {
//
//        if (!file_exists($path)) {
//            BaseHelper::Error('文件不存在');
//        }
//        //设置脚本运行时间（单位：秒） 0-没有时间限制
//        set_time_limit(0);
//        //memory_limit-设定一个脚本所能够申请到的最大内存字节数
//        ini_set('memory_limit', '2048M');
//
//        echo "初始: " . memory_get_usage() . "B<br>";
//        $t1 = microtime(true);
//
//        //表头
//        $excelHeader = $this->_getExcelHeader($type);
//
//        //读取excel
//        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
//        PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
//        $objPHPExcel = PHPExcel_IOFactory::load($path);
//
//        $t2 = microtime(true);
//        echo "load: " . memory_get_usage() . "B<br>";
//        echo 'load 耗时' . round($t2 - $t1, 3) . '秒<br>';
//
//        $sheet = $objPHPExcel->getSheet(0);
//
//        //获取数据
//        $data = array();
//        $num = 0;
//        $i = 0;
//        $transaction = '';
//        $t1 = microtime(true);
//        $model_1 = $this->getResourceModel($type);
//        $resource_1 = (new HyResource());
//
//        foreach ($sheet->getRowIterator() as $key => $row) {
//            //跳过第一行
//            if ($key == 1)
//                continue;
//            if ($i == 0) {
//                $transaction = Yii::$app->db->beginTransaction();
//            }
//            $cellIterator = $row->getCellIterator();   //得到所有列
//            $cellIterator->setIterateOnlyExistingCells(false); // Loopall cells, even if it is not set
//            foreach ($cellIterator as $k => $cell) {  //遍历列
//                $data[$excelHeader[$k]] = trim($cell->getCalculatedValue());
//            }
//            unset($cellIterator);
//            /*****************************************************/
//            //重复资源跳过
//
////            if ($data['url'] && $model->find()->where(['url' => $data['url']])->count()) {
////                continue;
////            }
//
//            //以后注释  测试自动生成
//            $data['res_code'] = $this->_resCode($type);
//            //存主表 生成编码  存资源表
//            $resource = clone  $resource_1;
//            $resource->type = $type;
//            $resource->res_title = $data['res_title'];
//            $resource->type = $type;
//            $resource->code = $data['res_code'];
//            $resource->save();
//
//            $data['res_id'] = $resource->primaryKey;
//
//            //获取分类
//            //$pid = ResourceClasses::find()->select('pid')->where(['id' => $data['cat_id2']])->asArray()->one();
//            $pid = ['pid' => 25];
//            if (empty($pid)) {
//                //移除最后一条主表 失败记录
//                HyResource::deleteAll(['id' => $data['res_id']]);
//                $position = $k + 1;
//                throw new \yii\db\Exception('新增资源：' . $key . '条，第' . $position . '条数据导入失败：资源分类号错误');
//            }
//            $data['cat_id'] = 1;
//            $data['cat_id2'] = 25;
//
//            $model = clone  $model_1;
//            if ($model->load($data, '') && $model->save()) {
//                $num++;
//                $i++;
//            } else {
//                //移除最后一条主表 失败记录
//                HyResource::deleteAll(['id' => $data['res_id']]);
//                $res = $model->getFirstErrors() ?: '数据格式不合规范';
//                if (is_array($res)) {
//                    $kkk = array_values($res);
//                    $res = $kkk[0];
//                }
//                $position = $k + 1;
//                throw new \yii\db\Exception('新增资源：' . $key . '条，第' . $position . '条数据导入失败：' . $res);
//            }
//
//            if ($i == 100) {
//                $transaction->commit();
//                $i = 0;
//            }
//
//            /*****************************************************/
//        }
//        if ($i > 0) {
//            $transaction->commit();
//        }
//
//        echo "读完: " . memory_get_usage() . "B<br>";
//        $t2 = microtime(true);
//        echo 'load 耗时' . round($t2 - $t1, 3) . '秒<br>';
//
//
//        $objPHPExcel->disconnectWorksheets();
//        echo "释放掉: " . memory_get_usage() . "B<br>";
//        var_dump($num);
//        die;
//
//    }


    /**
     * 读取并存储资源
     * @param $path
     * @param $type
     * @return int|void
     * @throws NotFoundHttpException
     * @throws \PHPExcel_Exception
     * @throws \PHPExcel_Reader_Exception
     * @throws \yii\base\ExitException
     * @throws \yii\db\Exception
     */
    public function ImportData($path, $type)
    {
        require_once 'HelpMethod';

        if (!file_exists($path)) {
            BaseHelper::Error('文件不存在');
        }
        //设置脚本运行时间（单位：秒） 0-没有时间限制
        set_time_limit(0);
        //memory_limit-设定一个脚本所能够申请到的最大内存字节数
        ini_set('memory_limit', '2048M');
        //echo "初始: " . memory_get_usage() . "B<br>";
        //读取excel
        $cacheMethod = PHPExcel_CachedObjectStorageFactory::cache_in_memory_gzip;
        PHPExcel_Settings::setCacheStorageMethod($cacheMethod);
        $objPHPExcel = PHPExcel_IOFactory::load($path);
        $sheet = $objPHPExcel->getSheet(0);
        $highestRow = $sheet->getHighestRow();
        $highestColumn = $sheet->getHighestColumn();
        //初始一次
        $transaction = '';
        $model = $this->getResourceModel($type);
        $resource = (new HyResource());
        //$t1 = microtime(true);
        // 获取一行的数据
        for ($row = 2; $row <= $highestRow; $row++) {
            // Read a row of data into an array
            $rowData = $sheet->rangeToArray('A' . $row . ':' . $highestColumn . $row, '', TRUE, FALSE);
            //存
            /*****************************************************/
            if ($row == 2 || $row % 100 == 1) {
                $transaction = Yii::$app->db->beginTransaction();
            }
            //选择对应资源的存入方式
            call_user_func('ResType_' . $type, clone $resource, clone $model, $rowData[0], $type, $this->_resCode($type));

            if (($row % 100 == 0) || $row == $highestRow) {
                $transaction->commit();
            }
            /*****************************************************/
        }

//        echo "读完: " . memory_get_usage() . "B<br>";
//        $t2 = microtime(true);
//        echo '读完 耗时' . round($t2 - $t1, 3) . '秒<br>';
        $objPHPExcel->disconnectWorksheets();
//        echo "释放掉: " . memory_get_usage() . "B<br>";
        var_dump(11);
        die;
    }

}